import React, { createElement, useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom'
import { Layout, Menu } from 'antd';
import * as Icon from '@ant-design/icons';
import { useDispatch } from 'react-redux'
import { updataMenuList } from '../../redux/reducers/tab'


const { Sider } = Layout;

// 动态获取icon(把字符串转换成图标组件)
const iconToElement = (name) => createElement(Icon[name])

const CommonAside = ({ collapsed }) => {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const location = useLocation()    //获取当前路由
  const [menuItems, setMenuItems] = useState([])
  const [selectedKeys, setSelectedKeys] = useState([''])

  const getParsedMenu  = () => {
    // 获取浏览器缓存的数据
    const menuData = sessionStorage.getItem('menu')
     // 解析缓存数据
    try {
      return menuData ? JSON.parse(menuData) : []
    } catch (error) {
      console.log('解析菜单数据失败', error)
      return []
    }
  }

  useEffect(() => {
    const parsedMenu = getParsedMenu()

    // 处理菜单的数据
    const items = parsedMenu.map(item => {
      // 没有子菜单
      const child = {
        key: item.path,
        icon: iconToElement(item.icon),
        label: item.label
      }
      // 有子菜单
      if (item.children) {
        child.children = item.children.map(i => ({
          key: i.path,
          icon: iconToElement(i.icon),
          label: i.label
        }))
      }
      return child
    })

    setMenuItems(items)
    // 初始化时，根据当前路由设置高亮
    setSelectedKeys([location.pathname])
  }, []);

  // 监听路由变化，同步更新高亮
  useEffect(() => {
    setSelectedKeys([location.pathname]);
  }, [location.pathname])

  // 添加数据到store的方法
  const setTabsList = (val) => {
    dispatch(updataMenuList(val))
  }

  const selectMenu = (e) => {
    // 获取最新的菜单数据
    const parsedMenu = getParsedMenu()

    let data
    parsedMenu.forEach(item => {
      // 找到当前的数据，此处的length是为了处理二级路由
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item
        // 如果有子菜单，获取子菜单的路径
        if (e.keyPath.length > 1) {
          data = item.children.find(child => child.path === e.key)    //find方法返回第一个满足条件的元素
        }
      }
    })
    if (data) {
      setTabsList({
        path: data.path,
        name: data.name,
        label: data.label
      })

      setSelectedKeys([e.key])
      navigate(e.key)
    } else {
      console.error('没有找到对应的菜单数据', e)
    }
  }

  return (
    // 导航区
    <Sider trigger={null} collapsed={collapsed}>
      <h3 className="app-name">{collapsed ? '后台' : '通用后台管理系统'}</h3>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKeys}
        items={menuItems}
        style={{ height: '100%' }}
        onClick={selectMenu}
      />
    </Sider>
  )
}

export default CommonAside;